<?php

namespace app\api\Service;

use app\common\library\Auth;
use addons\epay\library\Service;
use think\Db;
use think\Config;

class ShoporderService
{

    /**
     * 订单支付功能
     *
     * 该方法处理订单的支付逻辑，包括验证订单、更新订单状态和发起支付请求
     * 它首先验证用户身份和订单参数，然后根据订单类型构建支付请求参数，
     * 并调用微信支付接口发起支付请求如果订单金额为0，则直接更新订单为已支付状态
     *
     * @param array $data 包含订单ID和其他可能需要的数据
     * @return array 包含支付结果的数组，有'code'、'msg'和'data'字段
     */
    public static function orderPayment($data)
    {
        // 初始化认证类实例，用于获取用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;

        // 获取当前用户的微信OpenID
        $openid = $auth->openid;
        // 提取订单ID
        $order_id = $data['order_id'];
        // 默认支付方式为小程序
        $method = 'miniapp';

        // 检查是否绑定了微信OpenID
        if(!$openid) return ['code'=>0,'msg'=>'请先绑定微信','data'=>''];
        // 检查订单ID是否有效
        if(!$order_id) return ['code'=>0,'msg'=>'订单参数无效','data'=>''];

        // 查询订单信息，确保订单存在且属于当前用户
        $orderInfo = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->find();
        if (!$orderInfo) return ['code'=>0,'msg'=>'订单不存在','data'=>''];

        // 支付标题
        $title = "支付商城订单-{$orderInfo['order_no']}";

        // 处理订单金额为0的情况，直接更新订单为已支付
        if($orderInfo['payamount'] == 0){
            // 修改订单支付状态
            $orderInfo->trade_no = $orderInfo['order_no'];
            $orderInfo->paid = 1;
            $orderInfo->paytime = time();
            $result = $orderInfo->save();
            if($result){
                return ['code'=>1,'msg'=>'支付成功','data'=>''];
            }else{
                return ['code'=>0,'msg'=>'支付失败','data'=>''];
            }

            // 处理订单金额大于0的情况，准备发起支付请求
        }else{
            $type = 'wechat';
            // 构建微信支付回调URL
            $notifyurl = request()->domain() . '/addons/epay/index/shop_notifyx/paytype/' . $type;

            // 构建支付请求参数
            $params = [
                'amount'    => $orderInfo['payamount'],
                'orderid'   => $orderInfo['order_no'],
                'type'      => $type,
                'title'     => '【'.$title.'】',
                'method'    => $method,
                'openid'    => $openid,
                'notifyurl'    => $notifyurl,
            ];
            // 测试支付，固定金额为0.01元
            // $params['amount'] = 0.01;
            // 调用微信支付接口发起支付请求
            $response = Service::submitOrder($params);
            // 解析支付接口返回的响应
            $response = json_decode($response,true);
            return ['code'=>1,'msg'=>'操作成功','data'=>$response];
        }
    }

    /**
     * 获取用户订单列表
     *
     * 此函数用于根据用户请求的数据参数获取相应的订单列表信息
     * 它首先验证用户身份，然后根据订单类型查询相关订单详情
     * 最后返回格式化的订单列表信息
     *
     * @param array $data 包含分页信息和其他参数的数组
     * @return array 包含订单列表信息的数组
     */
    public static function getOrderLists($data){
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 设置每页显示的订单数量，默认为10条
        $limit = isset($data['limit']) && $data['limit'] ? $data['limit'] : 10;
        $status = $data['status'];

        if($status == -1){
            $where = ['user_id'=>$user_id];
        }elseif($status == 0){
            $where = ['user_id'=>$user_id,'paid'=>0,'status'=>0];
        }elseif($status == 1){
            $where = ['user_id'=>$user_id,'paid'=>1,'status'=>1];
        }elseif($status == 2){
            $where = ['user_id'=>$user_id,'paid'=>1,'status'=>2];
        }elseif($status == 3){
            $where = ['user_id'=>$user_id,'paid'=>1,'status'=>3];
        }elseif($status == 4){
            $where = ['user_id'=>$user_id,'paid'=>1,'status'=>0];
        }elseif($status == 100){
            $where = ['user_id'=>$user_id,'status'=>100];
        }elseif($status == 200){
            $where = ['user_id'=>$user_id,'paid'=>1,'status'=>200];
        }
//        return $where;
        // 查询用户订单信息，按创建时间降序排列，并进行分页处理
        $list = \app\admin\model\ShopOrder::where($where)->order('createtime desc')->field('id,order_no,payamount,paid,status')->paginate($limit)->each(function ($item, $key){
            $goods = \app\admin\model\ShopOrderItem::where(['order_id'=>$item['id']])->select();
            if($goods){
                $item['total_num'] = 0;
                foreach ($goods as $k=>$v){
                    $item['total_num'] += $v['goods_number'];
                }
                $item['goods'] = $goods;
            }else{
                $item['total_num'] = 0;
                $item['goods'] = [];
            }
            if($item['paid'] == 0 && $item['status'] == 0){
                $item['status_text'] = '未支付';
            }elseif($item['paid'] == 1 && $item['status'] == 0){
                $item['status'] = 4;
                $item['status_text'] = '待发货';
            }elseif($item['paid'] == 1 && $item['status'] == 1){
                $item['status_text'] = '待收货';
            }elseif($item['paid'] == 1 && $item['status'] == 2){
                $item['status_text'] = '已完成';
            }elseif($item['paid'] == 1 && $item['status'] == 3){
                $item['status_text'] = '已评价';
            }elseif($item['status'] == 100){
                $item['status_text'] = '已取消';
            }elseif($item['status'] == 200){
                $item['status_text'] = '已退款';
            }

        });
        // 返回成功信息和订单列表数据
        return ['code'=>1,'msg'=>'查询成功','data'=>$list];
    }

    /**
     * 获取订单详情
     *
     * 此函数根据提供的数据参数中的订单ID，查询并返回该订单的详细信息
     * 如果订单类型为安装，则获取安装相关的额外信息；如果订单类型为维修，则获取维修相关的额外信息
     *
     * @param array $data 包含订单ID的数组，用于查询订单详情
     * @return array 返回订单详情，包括订单基本信息、师傅信息（待补全）和订单类型特定信息
     */
    public static function getOrderDetails($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];

        // 查询订单表中匹配当前用户和给定订单ID的订单详情
        $details = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->field('id,address_id,order_no,amount,paytype,payamount,createtime,paytime,logistic,logistic_no,memo,status,paid')->find();

        // 如果找到了匹配的订单详情
        if($details){
            $goods = \app\admin\model\ShopOrderItem::where(['order_id'=>$details['id']])->select();
            if($goods){
                $details['total_num'] = 0;
                foreach ($goods as $k=>$v){
                    $details['total_num'] += $v['goods_number'];
                }
                $details['goods'] = $goods;
            }else{
                $details['total_num'] = 0;
                $details['goods'] = [];
            }
            $address = \app\admin\model\UserAddress::where(['id'=>$details['address_id']])->field('id,name,mobile,province_id,city_id,area_id,address')->find();
            if($address){
                $province = \app\admin\model\Area::where(['id'=>$address['province_id']])->value('name');
                $city = \app\admin\model\Area::where(['id'=>$address['city_id']])->value('name');
                $area = \app\admin\model\Area::where(['id'=>$address['area_id']])->value('name');
                $details['address'] = $province.$city.$area.$address['address'];
                $details['name'] = $address['name'];
                $details['mobile'] = $address['mobile'];
            }else{
                $details['address'] = '';
                $details['name'] = '';
                $details['mobile'] = '';
            }

            if($details['paid'] == 0){
                $details['status_text'] = '未支付';
            }elseif($details['paid'] == 1 && $details['status'] == 0 ){
                $details['status'] = 4;
                $details['status_text'] = '待发货';
            }elseif($details['paid'] == 1 && $details['status'] == 1){
                $details['status_text'] = '待收货';
            }elseif($details['paid'] == 1 && $details['status'] == 2){
                $details['status_text'] = '已完成';
            }elseif($details['paid'] == 1 && $details['status'] == 3){
                $details['status_text'] = '已评价';
            }elseif($details['status'] == 100){
                $details['status_text'] = '已取消';
            }elseif($details['status'] == 200){
                $details['status_text'] = '已退款';
            }
            $details['createtime_text'] = date('Y-m-d H:i:s',$details['createtime']);
            $details['paytime_text'] = date('Y-m-d H:i:s',$details['paytime']);
        }else{
            // 如果没有找到匹配的订单，返回空数组
            $details = [];
        }

        // 返回查询结果，包括状态码、消息和订单详情数据
        return ['code'=>1,'msg'=>'查询成功','data'=>$details];
    }

    /**
     * 取消订单功能
     *
     * 此函数用于处理用户请求取消特定订单的操作它首先验证订单是否存在以及当前用户的权限，
     * 然后根据订单状态判断是否可以取消如果订单可以被取消，它将更新订单状态并提交更改，
     * 否则将返回相应的错误信息整个过程使用事务处理，以确保数据的一致性和完整性
     *
     * @param array $data 包含订单ID的数组，用于指定需要取消的订单
     * @return array 返回结果数组，包含操作代码、消息和数据
     */
    public static function cancelOrder($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];

        // 根据订单ID和用户ID查询订单信息
        $order = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        // 如果订单状态为已完成，返回错误信息，表示订单不能被取消
        // if( $order['paid'] == 1 && $order['status'] == 0 ) return ['code'=>0,'msg'=>'订单已发货，请收到货物后选择退货','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            
            if($order['paid'] == 0){
                $order->refund_status = 1;
            }
            
            // 更新订单状态为已取消
            $order->status = 100;
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 还原库存
                $goodsInfo = \app\admin\model\ShopOrderItem::where(['order_id'=>$order_id])->field('goods_id,goods_number')->select();
                foreach($goodsInfo as $row){
                    $goods = \app\admin\model\ShopGoods::where(['id'=>$row['goods_id']])->field('stock_id')->find();
                    $stock_id = $goods['stock_id'];
                    if($stock_id){
                        $stock = \app\admin\model\ShopStock::where(['id'=>$stock_id])->find();
                        $stock->available_stock = $stock->available_stock + $row['goods_number'];
                        $stock->occupied_stock = $stock->occupied_stock - $row['goods_number'];
                        $stock->save();
                    }
                }

                $noticeParams = [
                    'event' => 'cancel_shop_order',
                    'params' => array (
                        'receiver_admin_ids' => '',
                        'receiver_admin_group_ids' => '',
                        'order_no' => $order['order_no'],
                    )];
                \Think\Hook::listen('send_notice', $noticeParams);

                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    public static function finishOrder($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];

        // 根据订单ID和用户ID查询订单信息
        $order = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        // 检查订单状态是否正确，只有当订单状态为2时，才继续执行后续逻辑
        if($order['status'] != 1 ) return ['code'=>0,'msg'=>'订单状态错误','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            // 更新订单状态为已取消
            $order->status = 2;
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                
                // 清除占用库存
                $goodsInfo = \app\admin\model\ShopOrderItem::where(['order_id'=>$order_id])->field('goods_id,goods_number')->select();
                foreach($goodsInfo as $row){
                    $goods = \app\admin\model\ShopGoods::where(['id'=>$row['goods_id']])->field('stock_id')->find();
                    $stock_id = $goods['stock_id'];
                    if($stock_id){
                        $stock = \app\admin\model\ShopStock::where(['id'=>$stock_id])->find();
                        $stock->occupied_stock = 0;
                        $stock->save();
                    }
                }
                
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

    }


    public static function afterSalesOrder($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];
        $reason = $data['reason'];
        $money = $data['money'];
        $memo = $data['memo'];
        $images = $data['images'];

        // 根据订单ID和用户ID查询订单信息
        $order = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        // 检查订单状态是否正确，只有当订单状态为2时，才继续执行后续逻辑
        if($order['status'] != 2 || $order['status'] != 3) return ['code'=>0,'msg'=>'订单状态错误','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            // 更新订单状态为已取消
            $order->status = 200;
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

    }

    // 撤销退款
    public static function cancelRefund($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];

        // 根据订单ID和用户ID查询订单信息
        $order = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        if($order['status'] != 200 ) return ['code'=>0,'msg'=>'订单状态错误','data'=>''];
        try{
            // 更新订单状态为已取消
            $order->status = 3;
            // 保存订单信息
            $res = $order->save();

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    public static function commentOrder($data)
    {
        // 实例化Auth类以进行用户身份验证
        $auth = Auth::instance();
        // 获取当前登录用户的ID
        $user_id = $auth->id;
        // 从输入数据中提取订单ID
        $order_id = $data['order_id'];
        $goods_id = $data['goods_id'];
        $star = isset($data['star']) ? $data['star'] : 5;
        $content = isset($data['content']) ? $data['content'] : '';
        $images = isset($data['images']) ? $data['images'] : '';

        // 根据订单ID和用户ID查询订单信息
        $order = \app\admin\model\ShopOrder::where(['id'=>$order_id,'user_id'=>$user_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$order) return ['code'=>0,'msg'=>'订单不存在','data'=>''];
        $goods = \app\admin\model\ShopGoods::where(['id'=>$goods_id])->find();
        // 如果查询结果为空，说明订单不存在，返回错误信息
        if(!$goods) return ['code'=>0,'msg'=>'商品不存在','data'=>''];
        // 检查订单状态是否正确，只有当订单状态为2时，才继续执行后续逻辑
        if($order['status'] != 2 ) return ['code'=>0,'msg'=>'订单未完成','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            // 更新订单状态为已取消
            $order->status = 3;
            // 保存订单信息
            $res = $order->save();


            $ret = \app\admin\model\ShoporderComments::create([
                'order_id'      =>  $order_id,
                'goods_id'      =>  $goods_id,
                'star'      =>  $star,
                'content'      =>  $content,
                'images'      =>  $images,
            ]);

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

    }

    // 测试回调
    public static function testNotifyx($data)
    {

        $paytype = 'wechat';
        $data['return_code'] = 'SUCCESS';
        $data['result_code'] = 'SUCCESS';
        $data['transaction_id'] = $data['out_trade_no'];
        $data['total_fee'] = 1;
        $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;


        if($paytype == 'wechat' && $data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS'){
            $order = \app\admin\model\Order::where('order_no', $data['out_trade_no'])->find();

            if(!$order){
                return json(['code' => 'FAIL', 'message' => '订单不存在'], 500, ['Content-Type' => 'application/json']);
            }

            //判断是否已支付过
            if( $order->paid == '1' ){
                return json(['code' => 'FAIL', 'message' => '订单已支付'], 500, ['Content-Type' => 'application/json']);
            }

            //修改订单状态
            $order->trade_no = $data['transaction_id'];

            $order->paid = 1;
            $order->paidtime = time();
//            $order->payamount = $payamount;
            $order->pay_price = $order->pay_price;
            $order_result = $order->save();

            // 冻结押金
            $user_id = $order->user_id;
            $user_deposit = Db::name('user_deposit')->where('user_id', $user_id)->find();
            $rental_deposit = $user_deposit['rental_deposit'];
            $order_over_freeze_money_days = Config::get('site.order_over_freeze_money_days');
            $expirationtime = time() + $order_over_freeze_money_days * 84600;
            $res = Db::name('user_deposit')->where('user_id', $user_id)->update(['freeze_money'=>$rental_deposit,'expirationtime'=>$expirationtime,'updatetime'=>time()]);
            // 更改车辆状态
            // $ret = \app\admin\model\Car::where(['tid'=>$order->tid])->update(['status'=>'normal','updatetime'=>time()]);


            return $res;

        }
    }



}